const Order = require('../../models/order')
const Goods = require('../../models/goods')
const Cart = require('../../models/cart')

const addOrder = async ctx => {
  const body = ctx.request.body
  const user = ctx.state.user
  await new Order({
    uid: user.id,
    orderGoods: body.goods,
    enTotal: body.enTotal,
    zhTotal: body.zhTotal
  }).save().then(res => {
    console.log('order save成功', res)
    // 这里下订单操作成功后 应该减去库存
    body.goods.forEach(async item => {
      // ! 注意mongoose里面的方法 会遵守这条语句 (如果传递回调，则执行查询，否则查询对象为returned.)
      // ! 也就是如果需要传递参数的方法 最好加上await 或者then 不然会执行不成功
      Goods.findOneAndUpdate({ _id: item.detail },
        { $inc: { inventory: -item.goods_num } }).then(res => {
        console.log('订单创建成功 goods库存更新成功')
      })
    })
    // 库存更新完后 还应该删除购物车的文档
    Cart.deleteMany({ _id: body.cid }).then(res => {
      console.log('订单创建成功 cart删除成功')
    })
    ctx.status = 200
    ctx.body = res
  }).catch(e => {
    console.log('addOrder报错', e)
    ctx.status = 500
    ctx.body = e
  })
}

module.exports = addOrder
